<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="工艺路线编码" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="engineering_path" column-name="code" :is-edit="id&&tag!='reviseEdition'" />
        </el-form-item>
        <el-form-item label="工艺路线名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入" clearable :disabled="tag=='reviseEdition'" />
        </el-form-item>
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="formData.versionCode" placeholder="请输入" clearable />
        </el-form-item>
        <!--        <el-form-item label="工艺类型" prop="typeCode">-->
        <!--          <DictSelect :band-value.sync="formData.typeCode" dict-type="processType" />-->
        <!--        </el-form-item>-->
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="processRequirement_bottom">
        <div class="processRequirement_bottom_tree">
          <div class="tree_header">
            <div class="formItem_header">
              工艺路线
              <div class="formItem_header_operate">
                <a class="formItem_header_operate_item" @click="chooseProcess">
                  <svg-icon icon-class="新增" />
                  <div class="item_name">添加</div>
                </a>
              </div>
            </div>

          </div>
          <div class="tree_container">

            <div class="processFlow_container">
              <div class="processFlow_container_main">
                <div ref="scrollRef" class="processFlow_container_main_right">
                  <div v-for="(item,index) in processFlowList" :key="index" :class="selectedIndex==index?'selected':''" class="right_item" @click="selectedIndex = index">

                    <div class="right_item_left">
                      <div class="right_item_left_left">
                        <div class="right_item_left_index">&nbsp;{{ index+1 }}&nbsp;</div>
                        <div class="right_item_left_name">{{ item.engineeringProcessCode }}/{{ item.engineeringProcessName }}</div>
                      </div>
                      <div class="right_item_left_right">
                        <a class="right_item_left_draggable"><svg-icon icon-class="行拖动" /></a>
                        <a class="right_item_left_delete" @click.stop="removeRow(index)"><svg-icon icon-class="行删除2" /></a>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="currentData&&currentData.engineeringProcessCode" class="processRequirement_bottom_detail">
          <div class="formItem_header">
            工序：  {{ currentData.engineeringProcessCode }}/{{ currentData.engineeringProcessName }}
          </div>
          <div class="detail_form">
            <div class="detail_form_item_double">
              <div class="detail_form_item_name bitian">标记工序</div>
              <div class="detail_form_item_radio">
                <el-radio-group v-model="currentData.productBySelf">
                  <el-radio label="1">自己生产</el-radio>
                  <el-radio label="0">外协</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="detail_form_item">
              <div class="detail_form_item_name bitian">是否送检</div>
              <div class="detail_form_item_radio">
                <el-radio-group v-model="currentData.toInspect">
                  <el-radio label="1">送检</el-radio>
                  <el-radio label="0">不送检</el-radio>
                </el-radio-group>
              </div>
            </div>
            <div class="detail_form_item">
              <div class="detail_form_item_name bitian">是否入库</div>
              <div class="detail_form_item_radio">
                <el-radio-group v-model="currentData.toWms">
                  <el-radio label="1">入库</el-radio>
                  <el-radio label="0">不入库</el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
          <div class="formItem_header formItem_header_padding">
            <div class="formItem_header2">
              计时
              <div class="formItem_header_tips">（计时或计件单价二选一即可，如果均填写，系统将默认以计件单价为准统计工资。）</div>
            </div>
          </div>
          <div class="detail_form">
            <div class="detail_form_item">
              <div class="detail_form_item_name">标准工时（时）</div>
              <div class="detail_form_item_input">
                <el-input v-model="currentData.standardWorkTime" placeholder="请输入" clearable />
              </div>
            </div>
            <div class="detail_form_item">
              <div class="detail_form_item_name">工时单价（元）</div>
              <div class="detail_form_item_input">
                <el-input v-model="currentData.workTimePrice" placeholder="请输入" clearable />
              </div>
            </div>
          </div>
          <div class="formItem_header formItem_header_padding">
            <div class="formItem_header2">
              计件
              <div class="formItem_header_tips">（计时或计件单价二选一即可，如果均填写，系统将默认以计件单价为准统计工资。）</div>
            </div>
          </div>
          <div class="detail_form">
            <div class="detail_form_item">
              <div class="detail_form_item_name">计件单价（元）</div>
              <div class="detail_form_item_input">
                <el-input v-model="currentData.unitPriceOfPiecework" placeholder="请输入" clearable />
              </div>
            </div>
          </div>

          <div class="formItem_header formItem_header_padding">
            生产过程
            <div class="formItem_header_operate">
              <a class="formItem_header_operate_item" @click="chooseProduceProcess">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteProduceProcess">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a>
            </div>
          </div>

          <div ref="table_container" class="table_container">
            <el-table
              ref="table3"
              :data="currentData.engineeringPathProcesses"
              stripe
              border
              @selection-change="selectionChange"
            >
              <el-table-column type="selection" width="70" align="center" />
              <el-table-column label="操作描述">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.operationDescription"
                    clearable
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column label="产品特性">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.productCharacter"
                    clearable
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column label="过程特性">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.courseCharacter"
                    clearable
                    placeholder="请输入"
                  />
                </template>
              </el-table-column>
              <el-table-column label="图号">
                <template slot-scope="scope">
                  <FileManage
                    :file-names.sync="scope.row.fileName"
                    :file-real-names.sync="scope.row.fileRealName"
                    :file-urls.sync="scope.row.fileUrl"
                    :row-index="scope.$index"
                    @fileName="setFileName2"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button v-if="tag!='reviseEdition'" @click.stop="onSubmit('0')">保存</el-button>
      <el-button @click.stop="onSubmit('1')">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo } from '@/api/engineeringManage/processFlow'
import Sortable from 'sortablejs'
import chooseProcess from './chooseProcess.vue'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    tag: {},
    defaultValue: {}
  },
  data() {
    return {
      selectedIndex: undefined,
      searchValue: '',
      loading: true,
      isShow: false,
      productBySelf: '1',
      toInspect: '1',
      toWms: '1',
      currentData: {
        productBySelf: '1',
        standardWorkTime: '',
        workTimePrice: '',
        unitPriceOfPiecework: '',
        toInspect: '1',
        toWms: '1'
      },
      selectionsAll: [],
      formData: {
        id: undefined,
        code: undefined,
        name: undefined,
        versionCode: undefined,
        typeCode: undefined,
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        remark: undefined,
        status: '1'
      },
      rules: {
        code: [
          { required: true, message: '工艺路线编码不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '工艺路线名称不能为空', trigger: 'change' }
        ],
        versionCode: [
          { required: true, message: '版本号不能为空', trigger: 'blur' }
        ]
      },
      processFlowList: []
    }
  },
  watch: {
    selectedIndex(newData, oldData) {
      // console.log('newData', newData)
      // console.log('oldData', oldData)
      if (oldData != undefined) {
        this.processFlowList[oldData] = this.$deepClone(this.currentData)
      }
      this.currentData = {}
      if (newData || newData == 0) {
        setTimeout(() => {
          Object.keys(this.processFlowList[newData]).forEach((key) => {
            this.$set(this.currentData, key, this.processFlowList[newData][key])
          })
        }, 100)
      }
    }
  },
  mounted() {
    if (this.tag == 'add') { // 新增
      this.loading = false
    }
    if (this.tag == 'edit') { // 编辑
      this.getInfo()
    }
    if (this.tag == 'copy') { // 复制
    }
    if (this.tag == 'reviseEdition') { // 升版
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          if (key != 'code') { this.formData[key] = res.data[key] }
        })
        this.processFlowList = res.data.data

        this.formData.id = ''
        this.formData.versionCode = ''

        setTimeout(() => {
          this.selectedIndex = 0
        }, 10)
        this.isShow = true
        this.loading = false
        this.rowDrop()
      })
    }
  },
  methods: {
    setFileName(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    },
    getInfo() {
      getInfo(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.processFlowList = res.data.data
        setTimeout(() => {
          this.selectedIndex = 0
        }, 10)
        this.isShow = true
        this.loading = false
        this.rowDrop()
      })
    },
    onSubmit(num) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let tag = true

          if (this.selectedIndex != undefined) {
            this.processFlowList[this.selectedIndex] = this.$deepClone(this.currentData)
          }
          if (!this.processFlowList || this.processFlowList.length == 0) {
            this.$message({
              message: '请添加工序',
              type: 'warning'
            })
            return
          }
          if (tag && (this.currentData.standardWorkTime)) {
            if (!this.SETTINGS.reg_integer.test(this.currentData.standardWorkTime)) {
              this.$message({
                message: '工时必须为整数',
                type: 'warning'
              })
              tag = false
            }
          }
          if (tag && (this.currentData.workTimePrice)) {
            if (!this.SETTINGS.reg_zero.test(this.currentData.workTimePrice)) {
              this.$message({
                message: '工时单价未正确填写',
                type: 'warning'
              })
              tag = false
            }
          }
          if (tag && (this.currentData.unitPriceOfPiecework)) {
            if (!this.SETTINGS.reg_zero.test(this.currentData.unitPriceOfPiecework)) {
              this.$message({
                message: '计件单价未正确填写',
                type: 'warning'
              })
              tag = false
            }
          }
          if (!tag) {
            return
          }

          const json = this.$deepClone(this.formData)
          json.status = num
          json.data = this.$deepClone(this.processFlowList)
          json.data.forEach((item, index) => {
            item.engineeringProcessRank = index + 1
            item.engineeringProcessNameIndex = json.data.length - index
          })

          addOrUpdate(json).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.refresh() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },

    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.processFlow_container_main_right')
      const _this = this
      Sortable.create(tbody, {
        handle: '.right_item_left_draggable',
        onEnd({ newIndex, oldIndex }) {
          _this.processFlowList[_this.selectedIndex] = _this.$deepClone(_this.currentData)
          _this.selectedIndex = undefined

          setTimeout(() => {
            const cacheData1 = _this.$deepClone(_this.processFlowList[oldIndex])
            const cacheTableData = _this.$deepClone(_this.processFlowList)
            cacheTableData.splice(oldIndex, 1)
            cacheTableData.splice(newIndex, 0, cacheData1)
            _this.processFlowList = []
            const cacheScroll = _this.$refs.scrollRef.scrollTop
            setTimeout(() => { // 加延时重置表格
              _this.processFlowList = cacheTableData
              setTimeout(() => {
                _this.$refs.scrollRef.scrollTop = cacheScroll
              }, 1)
            }, 1)
          }, 1)
        }
      })
    },
    removeRow(index) {
      this.selectedIndex = undefined
      this.$nextTick(() => {
        const cacheTableData = this.$deepClone(this.processFlowList)
        this.processFlowList = []
        cacheTableData.splice(index, 1)
        setTimeout(() => {
          this.processFlowList = cacheTableData
        }, 1)
      })
    },
    chooseProcess() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseProcess, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: undefined
          }
        },
        area: ['880px', '700px'],
        title: '选择工序', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },

    chooseProcessCallback(rows) {
      const oldData = this.$deepClone(this.processFlowList)
      rows.forEach(item => {
        item.productBySelf = '1'
        item.toInspect = '1'
        item.toWms = '1'
        item.standardWorkTime = ''
        item.workTimePrice = ''
        item.unitPriceOfPiecework = ''
        item.engineeringPathProcesses = []
        item.engineeringProcessId = item.id
        item.engineeringProcessCode = item.code
        item.engineeringProcessName = item.name
        delete item.id
        this.processFlowList.push(item)
      })
      this.$nextTick(() => {
        if (!oldData || oldData.length == 0) {
          this.selectedIndex = 0
        }
        this.rowDrop()
      })
    },
    checkBoxChange(val, index) {
      this.processFlowList[index].isOutsource = val
    },
    chooseProduceProcess() {
      const row = {
        operationDescription: '',
        productCharacter: '',
        courseCharacter: '',
        fileName: '',
        fileRealName: '',
        fileUrl: ''
      }
      this.currentData.engineeringPathProcesses.push(row)
    },
    deleteProduceProcess() {
      this.selectionsAll.forEach(item => {
        this.currentData.engineeringPathProcesses.splice(this.currentData.engineeringPathProcesses.indexOf(item), 1)
      })
    },
    setFileName2(...data) {
      this.currentData.engineeringPathProcesses[data[3]].fileName = data[0]
      this.currentData.engineeringPathProcesses[data[3]].fileRealName = data[1]
      this.currentData.engineeringPathProcesses[data[3]].fileUrl = data[2]
    },

    selectionChange(row) {
      this.selectionsAll = row
    }
  }
}
</script>

<style lang="less" scoped>
.main_main{
  display: flex;
  flex-direction: column;
  width: 100%;height: 100%;
}
.processFlow_container{
  border-top: 1px solid rgba(105, 105, 105, 0.2);height: 100%;
  .processFlow_container_header{
    height: 35px;
    font-size: 14px;color: #333333;
  }
  .processFlow_container_main{
    display: flex;height: 100%;
    .processFlow_container_main_left{
      position: relative;
      .search{
        position: fixed;
        padding: 10px 0;
        // top:10px ;
        // left:20px;
        width: 250px;
        background: white;
        // padding:0 20px;
      }
      /deep/ .el-input__prefix{
        display: unset !important;
      }
      /deep/ .el-input__inner{
        height: 30px;
        line-height: 30px;
        border-radius:15px;
        // margin-top: 10px;
        background: #EBF2FF;

      }
      .el-input__icon{
        line-height: 30px !important;
      }
      width: 300px;
      height: 280px;
      border-radius: 4px;
      padding: 0 20px 10px 20px;
      overflow-y: auto;
      .left_item{
        margin-top: 10px;
        width: 250px;
        height: 30px;
        border-radius: 15px;
        background: #EBF2FF;
        padding: 0 20px;
        display: flex;align-items: center;
        font-size: 14px;color: #333333;
        .left_item_name{
          overflow:hidden; //超出的文本隐藏
          text-overflow:ellipsis; //溢出用省略号显示
          white-space:nowrap; //溢出不换行
          width: 210px;
        }
      }
      .left_item:hover{
        background-color:  rgba(56, 123, 252, 0.5);
        color: white;
      }
    }
    .processFlow_container_main_middle{
      //flex: 1;
      width: 120px;
      display: flex;justify-content: center;align-items: center;
      .processFlow_container_main_middle_container{
        width: 80px;
        height: 50px;
        border-radius: 6px;
        background: #6095FD;
        display: flex;justify-content: center;align-items: center;
        font-size: 20px;
      }
    }
    .processFlow_container_main_right{
      width: 400px;
      height: 100%;
      border-radius: 4px;
      padding: 0 10px 10px 10px;
      overflow-y: auto;
      .right_item{
        margin-top: 10px;
        height: 40px;
        display: flex;align-items: center;
        font-size: 14px;color: #333333;
        cursor: pointer;
        .right_item_left{
          border-radius: 20px;
          background-color: #EBF2FF;
          height: 100%;
          flex: 1;
          display: flex;align-items: center;
          justify-content: space-between;
          .right_item_left_left{
            display: flex;align-items: center;
            .right_item_left_index{
              width: 24px;height: 24px;border-radius: 24px;
              margin-left: 10px;background-color: #BACBEC;
              display: flex;justify-content: center;align-items: center;
            }
            .right_item_left_name{
              width: 150px;
              font-size: 14px;color: #333333;
              padding-left: 10px;
              overflow:hidden; //超出的文本隐藏
              text-overflow:ellipsis; //溢出用省略号显示
              white-space:nowrap; //溢出不换行
            }
          }
          .right_item_left_right{
            display: flex;align-items: center;
            .right_item_left_draggable{
              font-size: 16px;
              margin-right: 20px;
            }
            .right_item_left_delete{
              font-size: 16px;
              margin-right: 10px;
            }
          }
        }
        .right_item_right{
          width: 80px;
          padding-right: 20px;
          display: flex;justify-content: flex-end;align-items: center;
        }
      }
      .right_item:hover,.right_item.selected{

        .right_item_left{
          background-color: rgb(56, 123, 252) !important;
          color: white !important;
          .right_item_left_left{
            color: white;
            .right_item_left_name{
              color: white;
            }
            .right_item_left_index{
              color: #333333;
            }
          }
        }
      }
    }
  }
}

.processRequirement_bottom{
  display: flex;
  border-top: 1px solid rgba(105,105,105,0.2);

  .processRequirement_bottom_tree{
    width: 30%;
    border-right: 1px solid rgba(105,105,105,0.2);
    .tree_header{
      height: 50px;
      margin: 0 20px;
      display: flex;align-items: center;
      font-size: 14px;
      color: #333333;
      border-bottom: 1px solid #387BFC;
      .formItem_header{
        padding: 0;
        font-size: 14px;
        .formItem_header_operate_item{
          height: 26px;
          font-size: 14px;
        }
      }
    }
    .tree_container{
      margin: 0 20px;overflow-y: overlay;
      height: calc(100% - 50px);

      .tree_container_item{
        // width: 100%;
        height: 40px;display: flex;align-items: center;
        padding-left: 20px;
      }
      .selected_row{

        background-color: rgba(56,123,252,1);
        color: white;
      }

      // .tree_container_item:hover{
      //   background-color: rgba(56,123,252,0.5);
      //   color: white;
      // }
    }
  }
  .processRequirement_bottom_detail{
    width: 70%;height: 100%;overflow-y: auto;
    .formItem_header_padding{
      margin-top: 20px;
    }
    .detail_form{
      display: flex;align-items: center;
      flex-wrap: wrap;
      .detail_form_item_double{
        width: calc(100% - 40px);
        display: flex;align-items: center;
        margin-left: 20px;
        margin-right: 20px;
        .detail_form_item_name{
          height: 30px;
          line-height: 30px;
          width: 120px;
          font-size: 14px;
          color: #666;
        }
        .detail_form_item_radio{
          width:calc(100% - 120px);
        }
      }
      .detail_form_item{
        width: calc(50% - 40px);
        display: flex;align-items: center;
        margin-left: 20px;
        margin-right: 20px;
        .detail_form_item_name{
          height: 30px;
          line-height: 30px;
          width: 120px;
          font-size: 14px;
          color: #666;
        }

        .detail_form_item_radio{
          width: calc(100% - 120px);
        }
        .detail_form_item_input{
          width: calc(100% - 120px);
          /deep/ .el-input__inner{
            height: 30px;
            line-height: 30px;
          }
        }
      }
    }
  }
}
.formItem_header2{
  display: flex;align-items: center;
  .formItem_header_tips{
    margin-left: 5px;
    display: flex;
    align-items: center;
    color: #CCCCCC;
    font-size: 14px;
  }

}
</style>
